package cc.bookcloud.tool.ocr.common.parsetext.feature;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import cc.bookcloud.tool.ocr.util.ocr.OcrTextParseUtil;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

/**
 * @Desc: 发票特征工厂
 * @Version: 2.0
 * @Author: John Goo
 * @Date: 2024/12/02 14:17
 **/
@Data
public class InvoiceFeatureBatchFactory {



    private List<InvoiceFeatureTemplateAbstract> featureList = new ArrayList<>();

    // 识别类型 false
    protected Boolean isIdentifyType = false;

    // ocr text 原始数据
    private JSONArray array;

    public InvoiceFeatureBatchFactory(){

    }



    /**
     * @Desc：发票txet数据分区（多张发票）
     * @Author：John Goo
     * @Date：2024/12/5 9:40
     * @param jsonStr
     * @return List<OcrTextInvoicePartitionEntity>
    */
    public List<OcrTextInvoicePartitionEntity> parsePartition(String jsonStr){
        // 1.找出发票特征（类型）对象
        List<InvoiceFeatureTemplateAbstract> featureList = extractInvoiceType(jsonStr);
       // System.out.println(JSON.toJSONString(featureList));

        // 2.根据发票特征对象坐标矩形区域范围分区分离（多张发票混合一起情况）
        List<OcrTextInvoicePartitionEntity> partitionEntityList = dataPartition(featureList);

        return partitionEntityList;

    }




    /**
     * @Desc：发票类型分析
    * @Author：John Goo
    * @Date：2024/12/2 15:39
    * @param text
    * @param pos
    * @return null-本行未找到;非空-找到发票类型
    */
    private InvoiceFeatureTemplateAbstract findCharacter(String text,int pos,JSONArray array){
       List<InvoiceFeatureTemplateAbstract> featureTemplateList = InvoiceFeatureTemplate.templateList();
        for(InvoiceFeatureTemplateAbstract feature : featureTemplateList){
            // 计算分数 100分机制
            feature.score(pos,text,array);
            // selected选中
            if(feature.getTotalScore() >= 100){
               // this.isIdentifyType = true;
                // 找到特征
                return feature;
            }
        }
       return null;
    }




    /**
     * @param featureList
     * @return JSONObject
     * @Desc：检测票据类型（单张）
     * @Author：John Goo
     * @Date：2024/11/28 9:35
     */
    public  List<OcrTextInvoicePartitionEntity> dataPartition(List<InvoiceFeatureTemplateAbstract> featureList) {
        List<OcrTextInvoicePartitionEntity>  partitionList = new ArrayList<>();

        // 数据按照发票所在位置分类
        if(featureList.size()>0 && array != null && array.size() > 0){

            for(InvoiceFeatureTemplateAbstract feature : featureList){
                 // min (x,y)
                int minX = feature.getCoordinate().getInteger(0);
                int minY = feature.getCoordinate().getInteger(1);
                // max(x,y)
                int maxX = minX + feature.getWidth();
                int maxY = minY + feature.getHeight();

                OcrTextInvoicePartitionEntity partitionEntity = new OcrTextInvoicePartitionEntity();
                partitionEntity.setType(feature.getType());
                partitionEntity.setTypeDesc(feature.typeDesc);
                partitionList.add(partitionEntity);
                // 遍历数组list,swap
                //List<Integer> recordUsedArrayIndex = new ArrayList<>();
                JSONArray tempArray = null;

                // ocr text 数据集
                for(int i=0; i< array.size(); i++){
                    JSONArray rowArray = array.getJSONArray(i);
                   // rowArray.getJSONArray(0).getJSONArray(0);
                    // 获取原始数组坐标
                    JSONArray p1 = rowArray.getJSONArray(0);
                    int x = p1.getJSONArray(0).getInteger(0);
                    int y = p1.getJSONArray(0).getInteger(1);
                    if(x <= maxX && x >= minX && y<= maxY && y>= minY){
                       String text =  rowArray.getJSONArray(1).getString(0);
                       // 多行数据
                       partitionEntity.addRow(i,text,p1);

                    }else{
                        // 迁移数据
                        if(tempArray == null){
                            tempArray = new JSONArray();
                        }
                        tempArray.add(rowArray);
                    }
                }
                // 清理array数组已使用过的数据
                this.array = tempArray;


            }
        }
        // 返回原数据
        return partitionList;
    }


    /**
     * @param jsonStr
     * @return JSONObject
     * @Desc：提取票据类型（单张）
     * @Author：John Goo
     * @Date：2024/11/28 9:35
     */
    public  List<InvoiceFeatureTemplateAbstract> extractInvoiceType(String jsonStr) {
        List<InvoiceFeatureTemplateAbstract> featureList = new ArrayList<>();
        // 票据特征描述
        /** ************* jsonStr解析处理 *******/
        JSONObject ocrData = JSON.parseObject(jsonStr, Feature.OrderedField);
        // 解析文本原始数组
        String arrayStr = ocrData.getString("ocrRet");
        JSONArray outArray = JSONArray.parseArray(arrayStr);
        if (outArray.size() > 0) {
            JSONArray array2 = outArray.getJSONArray(0);
            this.array = array2;
            // 票据行业
           // int total = array.size();
            // 分割，重新组合及合并

            for (int i = 0; i < array2.size(); i++) {
                JSONArray rowJson = array2.getJSONArray(i);
                //  array.getJSONArray(i).getJSONArray(1).get(0)
               // JSONObject row = new JSONObject();
                String text = (String) rowJson.getJSONArray(1).get(0);
                //System.out.println("=============== text :"+text+",size:"+array2.size()+",pos:"+i);
                // 特殊字符转换
                text = OcrTextParseUtil.chiSpecialStrTransferEn(text);
                InvoiceFeatureTemplateAbstract feature = findCharacter(text, i, array2);
                if (feature != null) {
                    featureList.add(feature);
                }
            }

        }
        return featureList;
    }



}
